package com.winchain.chainbill.bill.biz.transfer.rx;

import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.message.keyword.XfeApplySplitKeyword;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbXfe;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.transfer.vo.BillSplitEvent;
import com.winchain.chainbill.bill.biz.transfer.vo.BillXfe;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
public class BillXfeMsgSplitSubscriber extends OnErrorNotImplementedSubscriber<BillSplitEvent<CbXfe>> {
	public void onApplicationEvent(BillSplitEvent<CbXfe> t) {
		CbRec cbRec = t.getBill().getRec();
		List<BillXfe> child = (List<BillXfe>) t.getChildren();

		String sb = new String();

		String xfeDate = ((CbXfe) ((BillXfe) child.get(0)).getSource()).getXfeDate();

		String buyerId = ((CbXfe) ((BillXfe) child.get(0)).getSource()).getBuyerId();

		int length = child.size();

		BigDecimal xfeAmt = new BigDecimal(0);
		int count = 0;
		for (int i = 0; i < length; i++) {
			BillXfe billXfe = (BillXfe) child.get(i);

			CbXfe cbXfe = (CbXfe) billXfe.getSource();
			if (cbXfe != null) {
				if (count < 2) {
					String sellerNm = cbXfe.getSellerNm();
					sb = sb + sellerNm + ",";
				}
				xfeAmt = xfeAmt.add(cbXfe.getBillAmt());
				count++;
			}
		}
		if (length < 4) {
			sb = sb.substring(0, sb.length() - 1);
		} else {
			sb = sb.substring(0, sb.length() - 1) + "��";
		}
		String template = "MT01402";
		XfeApplySplitKeyword keyWord = new XfeApplySplitKeyword();
		keyWord.setBillAmt(String.valueOf(cbRec.getBillAmt()));

		keyWord.setContactorName(CommonDataUtil.getUserName());

		xfeDate = SysDateUtil.parseDate(xfeDate, "yyyyMMdd", "yyyy-MM-dd");
		keyWord.setXfeDate(xfeDate);
		keyWord.setSellerNms(sb);

		keyWord.setXfeAmt(String.valueOf(xfeAmt));

		String senderId = CommonDataUtil.getUserId();

		MessageSender.sendMessageByTmpl(senderId, template, keyWord, buyerId);
	}
}
